package com.attilax.order;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;

import aaaCfg.IocX4casher;
import bsh.StringUtil;

import com.attilax.acc.Acc;
import com.attilax.acc.AccNotExist;
import com.attilax.acc.AccService;
import com.attilax.acc.AccSrvAbs;
//import com.attilax.bet.AmountCalcService;
import com.attilax.data.DataStoreService;
import com.attilax.db.DBX;
import com.attilax.db.DbService;
import com.attilax.db.DbServiceQ5;
import com.attilax.exception.ExUtil;
import com.attilax.function.Function;
import com.attilax.io.filex;
import com.attilax.io.pathx;
import com.attilax.ioc.IocFacV3_iocx_iocutil;
import com.attilax.ioc.IocUtilV2;
import com.attilax.ioc.IocXq214;
import com.attilax.json.AtiJson;
import com.attilax.lang.FunctinImp;
import com.attilax.lang.Global;
import com.attilax.lang.SecuryEx;
import com.attilax.log.LogSvr;
import com.attilax.math.ADecimal;
import com.attilax.office.excelUtil;
import com.attilax.orm.AOrm;
import com.attilax.orm.AtiOrm;
import com.attilax.orm.AtiOrmAbs;
import com.attilax.sms.SmsService;
import com.attilax.sql.EmptyRzt;
import com.attilax.sql.SqlExeService;
import com.attilax.sql.SqlSecuryCheckor;
//import com.attilax.sql.DbService;
import com.attilax.store.StoreService;
import com.attilax.user.User;
import com.attilax.user.UserService;
import com.attilax.user.UserServiceAbs;
import com.attilax.util.DataMapper;
import com.attilax.util.PropX;
import com.attilax.web.ReqX;
import com.google.common.collect.Maps;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.attilax.trigger.Trigger_after;

/**
 * v3 add refuse and accept com.attilax.order.OrderService4jobus.refuse
 * 
 * com.attilax.order.RechargeOrderService  extends OrderService
 * @author attilax 2016年4月14日 下午12:36:44
 */
public class RechargeOrderService4gamepay  extends RechargeOrderService {
	@Inject
	SqlExeService sqlExeSrv1;
	public static void main(String[] args)  {
		System.out.println("--fxx000  ");
		System.setProperty("apptype", "jobus");
		System.setProperty("prj", "jobus");
		System.setProperty("cfgfile", "pay.ini");
		RechargeOrderService srv = IocFacV3_iocx_iocutil
				.getBean(RechargeOrderService.class);

		// System.out.println(srv.refuse("0301_152839_178"));
		// System.out.println(srv.accept("0301_152839_178"));

		 
		//
	//	int finishMsg = srv.insert("123466",125,1598);
			//	 t();
	

		System.out.println("--f");

	}

	private static String t() {
		RechargeOrderService srv = IocFacV3_iocx_iocutil
				.getBean(RechargeOrderService.class);
		String finishMsg = null;
		try {
		 	finishMsg = (String) srv.finish("20161024_1840165", 5);
		} catch (CantFindOrder e) {
			 
			ExUtil.throwExV2(e);
		}
		System.out.println(finishMsg);
		return finishMsg;
	}

//	@Inject
//	DataStoreService storeSvr;  //ok

	@Inject
	UserServiceAbs userSvr;
	@Inject
	AccSrvAbs accSvr;
	//@Inject
	//AmountCalcService amoutCalcSvr;
	@Inject
	private LogSvr logSvr;

	// @Inject @Named("order_service_dataMaper")
	// @ImplementedBy(FunctinImp.class) should ostion in interface java hto..
	// public Function dataMaper;
	@Inject
	public Trigger_after trig_bef;
	@Inject
	public Trigger_after trig_aft;

	public int insert(HttpServletRequest req) {
		return insert(ReqX.toMap(req));
	}

	public int insert(Map order) {
		return 0;
//		if (userSvr == null)
//			throw new RuntimeException("#userSvr_is_null");
//		if (accSvr == null)
//			throw new RuntimeException("#accSvr_is_null");
//		if (amoutCalcSvr == null)
//			throw new RuntimeException("#amoutCalcSvr_is_null");
//
//		if (userSvr.isNotLogin()) {
//			throw new RuntimeException(" not login 没登录,请先登录..#not_login");
//		}
//
//		User u = userSvr.getLoginUser();
//		Acc a = accSvr.getAcc(u.id);
//
//		BigDecimal needMoney = amoutCalcSvr.calc(order);
//
//		if (new ADecimal(needMoney).biggerEqualThan(a.amount))
//			throw new RuntimeException(
//					"  amount not enough 金额不足够 ..#amount_not_enough ");
//
//		// /...insert
//		order.put("$op", "insert");
//		order.put("order_id", filex.getUUidName());
//		order.put("order_money", needMoney);
//		trig_bef.apply(order);
//
//		storeSvr.insert(order);
//
//		int rzt = accSvr.reduceAmount(u.id.toString(), needMoney.doubleValue());
//		logSvr.log(order);
//		return rzt;

	}

	@Inject
	AtiOrmAbs ormx;

	private Object finish_stat;

	/**
	 * for req
	attilax    2016年4月20日  下午4:11:03
	 * @return
	 * @throws CantFindOrder 
	 */
	public Object finish() throws CantFindOrder 
	{
		HttpServletRequest	 req=Global.req.get();
		return finish(ReqX.toMap(req));
	}
	
	public Object finish(Object orderNo, Object amount) throws CantFindOrder {
	 
		   assert orderNo!=null;   assert amount!=null;
		   
		   
		String order_id = (String) SqlSecuryCheckor.val(orderNo);
		if (finished(order_id))
		{
			this.finish_stat="already_finish";
			System.out.println(" order id is finish :"+orderNo);
			return "ok";
		}
			 
		
		//-------check money equ
		if(amount==null)
			throw new SecuryEx(" feeFromUrl is null");
	
		
		BigDecimal money_frmDb=new BigDecimal(order.get("rmb").toString());
		BigDecimal money_frmUrl=new BigDecimal( amount.toString());
		BigDecimal money_frmDb_unitIsPercent=money_frmDb.multiply(new BigDecimal (100));
		if( money_frmDb_unitIsPercent.compareTo(money_frmUrl)!=0 )
			throw new FeeNotEquEx(" froom url total_fee:"+amount.toString()+",moneyFrmDb:"+ money_frmDb+",moneyFrmDb_percent:"+ money_frmDb_unitIsPercent );
		
		PropX px=new PropX( pathx.webAppPath()+"/"+System.getProperty("cfgfile") );
		String sql=px.getProperty("rechgOrder.finishOrder");
		sql=sql.replace("$no$", orderNo.toString());	

		Object r =  sqlExeSrv1.executeUpdate(sql);
	//	r=1;// for test
		if ((Integer) r == 1)
		{
			String uid=order.get("accountId").toString();
			BigDecimal money=new BigDecimal( order.get("rmb").toString());
			try {
				accSvr.addAmount(uid, money);
			} catch (AccNotExist e) {
				ExUtil.throwExV2(e,"AccNotExist uid:"+uid);
			}
			
			if(afterRun!=null)
				afterRun.run();
			return "ok";
			
		}
		throw new OrderFinishEx(" order finish ex,ret code:"+r +" sql:"+sql);
	
		 
	}
	public Runnable afterRun;
	public Object finish(Map m) throws CantFindOrder {
		// if(StringUtils.isEmpty((String)m.get("$where")) )
		// throw new RuntimeException("no $where contion..");
		String order_id = (String) SqlSecuryCheckor.val(m.get("order_id"));
		if (finished(order_id))
			return "already_finish";
		
		//-------check money equ
		if(m.get("feeFromUrl")==null)
			throw new SecuryEx(" feeFromUrl is null");
		BigDecimal money_frmDb=(BigDecimal) ormx.querySingleRow.get("money");
		BigDecimal money_frmUrl=new BigDecimal( m.get("feeFromUrl").toString());
		if( money_frmDb.compareTo(money_frmUrl)!=0 )
			throw new FeeNotEquEx(" froom url total_fee.dbfee:"+m.get("feeFromUrl").toString()+"-"+  ormx.querySingleRow.get("money") );
		
		m.put("stat", 1);

		String where = " order_id='$order_id$'".replace("$order_id$",
				SqlSecuryCheckor.val(m.get("order_id")));
		m.put("$where", where);
		m.remove("order_id");
		// m.put("stat",1);
		ormx.m = m;
		ormx.setOp(ormx.update);
		ormx.setTable("orderv2");
		

		Object r =1;// ormx.exe(m);
		if ((Integer) r == 1)
		{
			String uid=ormx.querySingleRow.get("uid").toString();
			BigDecimal money=(BigDecimal) ormx.querySingleRow.get("money");
			try {
				accSvr.addAmount(uid, money);
			} catch (AccNotExist e) {
				ExUtil.throwExV2(e);
			}
			
			if(afterRun!=null)
				afterRun.run();
			return "ok";
			
		}
		throw new OrderFinishEx(" order finish ex");

	}

	/**
	attilax    2016年4月21日  下午9:29:02
	 * @param string
	 * @return
	 */
	private Exception FeeNotEquEx(String string) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean finished(String order_id) throws CantFindOrder {
		PropX px=new PropX( pathx.webAppPath()+"/"+System.getProperty("cfgfile") );
		String sql=px.getProperty("rechgOrderQuery");
		String s = sql.replace("$no$", order_id);
		Map m;
		try {
			m = sqlExeSrv1.executeQueryFirstRow(s);
			
		} catch (EmptyRzt e) {
			 throw new CantFindOrder("order id:"+order_id);
		}
		order=m;
	//	 ormx.tabletype("sql").querySingleRow(s).querySingleRow;
//		if (m == null)
//			throw new CantFindRechargeOrder("order id:" + order_id);
 		String stat = m.get("status").toString();
		if (stat.equals("1"))
			return true;
		if (stat.equals("0"))
			return false;
		throw new RechargeOrderStatErr(" order.stat:" + order_id + "." + stat);
	}
	
 
	public List<Map> query(Map order) {

		if (userSvr.isNotLogin()) {
			throw new RuntimeException(" not login 没登录,请先登录..#not_login");
		}
		User u = userSvr.getLoginUser();

		return null;

		// /...insert
		// return accSvr.reduceAmount(u.id.toString(), needMoney.doubleValue());

	}

	@Deprecated
	public String query2json(Map order) {

		return AtiJson.toJson(query(order));

		// /...insert
		// return accSvr.reduceAmount(u.id.toString(), needMoney.doubleValue());

	}

	public String finishV2_wzRoomCard(Object no, Object money) throws CantFindOrder {
		 this.afterRun=()->{
			 
			// ormx.setTable("ttt").setOp(ormx.update);
			 sqlExeSrv1.execSql_retInt("");
			 
		 };
		 
		return (String) finish(no,money);
	}

	

}
